/*
 * Galaxium Messenger
 * Copyright (C) 2008 Paul Burton <paulburton89@gmail.com>
 * 
 * License: GNU General Public License (GPL)
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

using System;
using System.Collections.Generic;
using System.IO;

using Gdk;
using Gtk;
using Glade;

using Anculus.Core;

using Galaxium.Core;

namespace Galaxium.Protocol.Msn.GtkGui
{
	public partial class MsnPreferenceWidget
	{
		//[Widget ("btnAdd")] ToolButton _btnAdd = null;
		//[Widget ("btnRemove")] ToolButton _btnRemove = null;
		//[Widget ("btnPreview")] ToolButton _btnPreview = null;
		[Widget ("tvWinks")] TreeView _tvWinks = null;
		
		void InitWinks ()
		{
			_tvWinks.AppendColumn("Preview", new CellRendererPixbuf (), new TreeCellDataFunc (RenderPreview));
			_tvWinks.AppendColumn("Name", new CellRendererText (), new TreeCellDataFunc (RenderName));
			
			ListStore store = new ListStore (typeof (MsnWink));
			
			List<IConfigurationSection> toRemove = new List<IConfigurationSection> ();
			foreach (IConfigurationSection account in _config.Sections)
			{
				foreach (IConfigurationSection section in account["Winks"].Sections)
				{
					string filename = section.GetString ("Filename");
					
					MsnWink wink = MsnWink.FromPackage (null, filename);
					
					if (wink == null)
					{
						Log.Warn ("Unable to load wink {0}", filename);
						Log.Warn ("Removing invalid wink from cache");
						
						if (File.Exists (filename))
							File.Delete (filename);
						
						toRemove.Add (section);
						
						continue;
					}
					
					store.AppendValues (wink);
				}
			}
			
			foreach (IConfigurationSection section in toRemove)
				section.Parent.RemoveSection (section.Name);
			
			_tvWinks.Model = store;
		}
		
		void RenderPreview (TreeViewColumn column, CellRenderer cell, TreeModel model, TreeIter iter)
		{
			MsnWink wink = (MsnWink)model.GetValue(iter, 0);
			
			try
			{
				(cell as CellRendererPixbuf).Pixbuf = new Pixbuf (wink.Thumbnail);
			}
			catch
			{
				Log.Warn ("Unable to generate preview for {0} ({1})", wink.Sha, BaseUtility.GetHashedName (wink.Sha));
			}
		}
		
		void RenderName (TreeViewColumn column, CellRenderer cell, TreeModel model, TreeIter iter)
		{
			MsnWink wink = (MsnWink)model.GetValue(iter, 0);
			
			(cell as CellRendererText).Text = wink.Friendly;
		}
		
#region Glade Event Handlers
#pragma warning disable 169
		void AddButtonClicked (object sender, EventArgs args)
		{
			FileChooserDialog dialog = new FileChooserDialog ("Choose a wink", (Gtk.Window)_nativeWidget.Toplevel, FileChooserAction.Open, new object[] { "Cancel", ResponseType.Cancel, "Accept", ResponseType.Accept });
			FileFilter filter = new FileFilter ();
			filter.AddPattern ("*.[mM][cC][oO]");
			dialog.Filter = filter;
			dialog.SetCurrentFolder (Environment.GetFolderPath (Environment.SpecialFolder.Personal));
			
			if (dialog.Run () == (int)ResponseType.Accept)
			{
				MsnWink wink = WinkStorageUtility.AddWink (null, dialog.Filename, true);
				
				if (wink != null)
				{
					(_tvWinks.Model as ListStore).AppendValues (wink);
				}
				else
				{
					//TODO: Show error message
					MessageDialog errdialog = new MessageDialog (_nativeWidget.Parent as Gtk.Window,
					                                             DialogFlags.Modal, MessageType.Error, ButtonsType.Ok,
					                                             "The file you chose is not a valid wink");
					
					errdialog.Run ();
					errdialog.Destroy ();
				}
			}
			
			dialog.Destroy();
		}
		
		void RemoveButtonClicked (object sender, EventArgs args)
		{
			TreeIter iter;
			_tvWinks.Selection.GetSelected (out iter);
			
			if (iter.Equals (TreeIter.Zero))
				return;
			
			MsnWink wink = (MsnWink)(_tvWinks.Model as ListStore).GetValue (iter, 0);
			(_tvWinks.Model as ListStore).Remove (ref iter);
			
			WinkStorageUtility.RemoveWink (wink);
		}
		
		void PreviewButtonClicked (object sender, EventArgs args)
		{
			TreeIter iter;
			_tvWinks.Selection.GetSelected (out iter);
			
			if (iter.Equals (TreeIter.Zero))
				return;
			
			MsnWink wink = (MsnWink)(_tvWinks.Model as ListStore).GetValue (iter, 0);
			
			new WinkDisplay (wink, _tvWinks.Parent).Show ();
		}
#pragma warning restore 169
#endregion
	}
}
